package model;

import java.io.IOException;

import org.restlet.Client;
import org.restlet.data.Method;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.StringRepresentation;

import config.Config;

public class ServerConnector {

	private static Client client = new Client(Config.PROTOCOL);

	public static String getResponse(String category, String jsonRequest) {
		Response response = buildUri(category, jsonRequest);
		String result = "";
		if (response.isEntityAvailable()) {
			try {
				result = response.getEntity().getText();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	private static Response buildUri(String category, String jsonRequest) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("http://");
		stringBuilder.append(Config.HOST).append(":").append(Config.PORT);
		stringBuilder.append("/").append(category).append("/");
		return handleRequest(
				new Request(Method.POST, stringBuilder.toString()), jsonRequest);
	}

	private static Response handleRequest(Request requestURI, String jsonRequest) {
		Representation representation = new StringRepresentation(jsonRequest);
		requestURI.setEntity(representation);
		Response response = client.handle(requestURI);
		return response;
	}
}